package com.lottery.api.controller.member;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lottery.api.annotation.CoerceLoginAop;
import com.lottery.api.service.MemberInfoService;
import com.lottery.api.service.OrderInfoApiService;
import com.lottery.common.contants.Constants;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.entity.DepositRecord;
import com.lottery.common.entity.MemberInfo;
import com.lottery.common.entity.OrderInfo;
import com.lottery.common.entity.SysConfig;
import com.lottery.common.model.BaseModel;
import com.lottery.common.service.*;
import com.lottery.common.utils.RedisUtils;
import com.lottery.pay.Constants.WeixinConstant;
import com.lottery.pay.service.PaymentRecordsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

import static com.lottery.common.contants.Constants.*;

/**
 * @author o551wwl
 */
@RestController
@RequestMapping("/order")
@Slf4j
@Api(value = "/order",tags="订单操作类")
public class OrderInfoController {
    private ReQueryResult result = new ReQueryResult();

    @Resource
    private MemberInfoService mis;
    @Resource
    private DecryptToObjectService decryptToObjectService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderInfoApiService orderInfoApiService;
    @Autowired
    private PaymentRecordsService paymentRecordsService;
    @Autowired
    private DepositRecordService depositRecordService;

    @Value("${base.upload.path}")
    private String uploadPath;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @CoerceLoginAop
    @ApiOperation(value = "余额充值、消费记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type",value = "类型  1 充值 2 消费",dataType="Integer"),
            @ApiImplicitParam(name = "index",value = "页码 ",dataType="Integer"),
            @ApiImplicitParam(name = "length",value = "长度",dataType="Integer"),
    })
    @RequestMapping(value = "/records", method = RequestMethod.GET)
    public ReQueryResult<OrderInfo> balanceRecords(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,
                                       Integer index,Integer length,  Integer type){
        result=new ReQueryResult();
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id","order_num","amount","pay_type","title","create_time").eq("member_id",memberInfo.getId())
                .eq("status",TYPE_ZERO);
        if (type==null){
            queryWrapper.apply(" (pay_type=3 or order_type=4)");
        }else if (type==TYPE_ONE){
            queryWrapper.eq("order_type",TYPE_FOUR);
        }else if (type==TYPE_TWO){
            queryWrapper.eq("pay_type",TYPE_THREE);
        }
        queryWrapper .orderByDesc(" id ");
        Page<OrderInfo> page = new Page<>(index,length);
        IPage<OrderInfo> list=orderInfoService.page(page,queryWrapper);
        result.setData(list);
        result.success(SUCCESS_DESC);
        return  result;
    }


    @CoerceLoginAop
    @ApiOperation(value = "消费明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "订单id",dataType="Integer"),
    })
    @RequestMapping(value = "/consume/{id}", method = RequestMethod.GET)
    public ReQueryResult<OrderInfo> consumeRecords(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,
                                        @PathVariable Integer id){
        result=new ReQueryResult();
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id","order_num","amount","pay_type","title","create_time","type_value","order_type")
                .eq("id",id).eq("member_id",memberInfo.getId()).eq("status",TYPE_ZERO);
        OrderInfo info=orderInfoService.getOne(queryWrapper);
//        info.setTypeValue(info.getTitle());
        if (info.getOrderType()==TYPE_TWO){
            String[] str=info.getTypeValue().split(",");
            StringBuilder sb=new StringBuilder("");
            for(String s:str){
                sb.append(RedisUtils.getConfigFromRedis(s, SysConfig.class).getRemark()).append(" ");
            }
            info.setTypeValue(sb.toString());
        }else{
            info.setTypeValue(info.getTitle());
        }
        result.setData(info);
        result.success(SUCCESS_DESC);
        return  result;
    }

//    @CoerceLoginAop
//    @ApiOperation(value = "余额充值记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "index",value = "页码 ",dataType="Integer"),
//            @ApiImplicitParam(name = "length",value = "长度",dataType="Integer"),
//    })
//    @RequestMapping(value = "/balance/recharge/{index}", method = RequestMethod.GET)
//    public ReQueryResult balanceRecharge(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,@PathVariable Integer index,Integer length){
//        result=new ReQueryResult();
//        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("memberId",memberInfo.getId()).eq("order_type",TYPE_FOUR).eq("status",TYPE_ZERO)
//                .apply("  order by id desc ");
//        Page<OrderInfo> page = new Page<>(index,length);
//        IPage<OrderInfo> list=orderInfoService.page(page,queryWrapper);
//        result.setData(list);
//        result.success(SUCCESS_DESC);
//        return  result;
//    }
//
//    @CoerceLoginAop
//    @ApiOperation(value = "余额消费记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "index",value = "页码 ",dataType="Integer"),
//            @ApiImplicitParam(name = "length",value = "长度",dataType="Integer"),
//    })
//    @RequestMapping(value = "/balance/expend/{index}", method = RequestMethod.GET)
//    public ReQueryResult balanceExpend(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,@PathVariable Integer index,Integer length){
//        result=new ReQueryResult();
//        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("memberId",memberInfo.getId()).eq("pay_type",TYPE_THREE).eq("status",TYPE_ZERO)
//                .apply("  order by id desc ");
//
//        Page<OrderInfo> page = new Page<>(index,length);
//        IPage<OrderInfo> list=orderInfoService.page(page,queryWrapper);
//        result.setData(list);
//        result.success(SUCCESS_DESC);
//        return  result;
//    }


    @CoerceLoginAop
    @ApiOperation(value = "金币消费记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index",value = "页码 ",dataType="Integer"),
            @ApiImplicitParam(name = "length",value = "长度",dataType="Integer"),
    })
    @RequestMapping(value = "/gold/expend/{index}", method = RequestMethod.GET)
    public ReQueryResult goldExpend(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,@PathVariable Integer index,Integer length){
        result=new ReQueryResult();
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("memberId",memberInfo.getId()).eq("pay_type",TYPE_FOUR).eq("status",TYPE_ZERO)
                .apply("  order by id desc ");
        Page<OrderInfo> page = new Page<>(index,length);
        IPage<OrderInfo> list=orderInfoService.page(page,queryWrapper);
        result.setData(list);
        result.success(SUCCESS_DESC);
        return  result;
    }


    /**
     * 申请提现
     * @param request
     * @return
     */
    @ApiOperation(value = "申请提现")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "depositType",value = "提现类型 1 支付宝 2 微信 3银行",dataType="Integer"),
            @ApiImplicitParam(name = "depositAccount",value = "提现账号 ",dataType="String"),
            @ApiImplicitParam(name = "depositName",value = "提现人姓名",dataType="String"),
            @ApiImplicitParam(name = "bankCard",value = "银行",dataType="String"),
            @ApiImplicitParam(name = "bankCardAddress",value = "开户行",dataType="String"),
            @ApiImplicitParam(name = "money",value = "提现金额",dataType="Integer"),

    })
    @RequestMapping(value = "/deposit", method = RequestMethod.POST)
    @CoerceLoginAop
    public ReQueryResult deposit(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo, DepositRecord record){
        result=new ReQueryResult();
        QueryWrapper<MemberInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("gold").eq("id",memberInfo.getId());
        MemberInfo info=mis.getOne(queryWrapper);
        if(info.getGold().intValue()<record.getMoney()){
            result.error("提现金币超过余额");
            return  result;
        }
        depositRecordService.save(record);
        result.success(Constants.SUCCESS_DESC);
        return  result;
    }


    @CoerceLoginAop
    @ApiOperation(value = "创建支付订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeType",value = "支付方式 1app 2 h5 3 支付宝web 4 jsapi 5小程序 6 native ",dataType="Integer"),
            @ApiImplicitParam(name = "orderType",value = "订单类型 1购买推荐 2购买定制 3购买会员  4 充值",dataType="Integer"),
            @ApiImplicitParam(name = "typeValue",value = "关联id 购买类型取值id",dataType="String"),
            @ApiImplicitParam(name = "valueDesc",value = "关联名称",dataType="String"),
            @ApiImplicitParam(name = "payType",value = "支付类型 1 支付宝 2微信 3余额 4 金币",dataType="Integer"),
            @ApiImplicitParam(name = "amount",value = "金额 仅充值时必填",dataType="Integer"),
    })
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ReQueryResult createOrder(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,@ApiIgnore() OrderInfo orderInfo){
        result=new ReQueryResult();

        boolean flag = RedisUtils.checkRedisLock("order"+memberInfo.getId(), 2);
        if (!flag) {
            result.error("请勿重复点击");
            return result;
        }
        if (orderInfo.getOrderType()==TYPE_FOUR){
            if (orderInfo.getAmount()==null||orderInfo.getAmount().compareTo(BigDecimal.ZERO)<=0){
                result.error(RECHARGE_AMOUNT_FAIL);
                return result;
            }
        }

        orderInfo.setMemberId(memberInfo.getId());
        orderInfo.setPhone(memberInfo.getPhone());
        result=orderInfoApiService.createOrder(orderInfo,request);
        return  result;
    }



    /**
     * 支付宝支付回调接口
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/alipayResult", method = RequestMethod.POST)
    public String alipayResult(HttpServletRequest request, HttpSession session) {
        log.info("————resualipayResultlt————");
        try {
            result=paymentRecordsService.resultAll(Constants.TYPE_ONE,request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.error(ExceptionUtils.getFullStackTrace(e));
            result.error(Constants.INSIDE_WRONG_DESC);
            return "";
        }
        return result.getData().toString();
    }



    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @RequestMapping(value = "wxResult", method = {RequestMethod.POST})
    public String wxResult(HttpServletRequest request) {
        log.info("------------ order wxResult --------------");
        try {
            result=paymentRecordsService.resultAll(Constants.TYPE_TWO,request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" PAYOFF_RETURN_MSG_ERROR ");
            log.error(e.toString());
            return WeixinConstant.PAYOFF_RETURN_MSG_ERROR;
        }
        log.info("PAYOFF_RETURN_MSG  is {}", JSON.toJSONString(result));
        if (result.getResultCode().equals(TYPE_ZERO_ZERO_STR)) {
            return WeixinConstant.PAYOFF_RETURN_MSG;
        } else {
            return  WeixinConstant.PAYOFF_RETURN_MSG_ERROR;
        }
    }
    
}
